<?php
// ========================== 文件说明 ==========================//
// 本文件说明：前后台公共函数
// --------------------------------------------------------------//
// 本程序作者：angel
// --------------------------------------------------------------//
// 本程序版本：SaBlog-X Ver 1.6
// --------------------------------------------------------------//
// 本程序主页：http://www.sablog.net
// ========================== 开发环境 ==========================//
// register_globals = Off
// --------------------------------------------------------------//
// magic_quotes_gpc = On
// --------------------------------------------------------------//
// safe_mode = On
// --------------------------------------------------------------//
// Windows server 2003 & Linux & FreeBSD
// --------------------------------------------------------------//
// Apache/1.3.33 & PHP/4.3.2 & MySQL/4.0.17
// --------------------------------------------------------------//
// Apache/1.3.34 & PHP/4.4.1 & MySQL/5.0.16
// --------------------------------------------------------------//
// Apache/2.0.55 & PHP/5.1.1 & MySQL/5.0.15
// --------------------------------------------------------------//
// Copyright (C) Security Angel Team All Rights Reserved.
// ==============================================================//

if(!defined('SABLOG_ROOT')) {
	exit('Access Denied');
}

// 去除转义字符
function sax_stripslashes($array) {
	if (is_array($array)) {
		foreach ($array as $k => $v) {
			$array[$k] = sax_stripslashes($v);
		}
	} else if (is_string($array)) {
		$array = stripslashes($array);
	}
	return $array;
}

// 添加转义
function sax_addslashes($string) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = sax_addslashes($val);
		}
	} else {
		$string = addslashes($string);
	}
	return $string;
}


//格式化时间
function sadate($format,$timestamp=''){
	global $options,$timeoffset;
	!$timestamp && $timestamp = time();
	return gmdate($format,$timestamp+$timeoffset*3600);
}

// 获得散列
function formhash($specialadd = '') {
	global $sax_user, $sax_uid, $sax_pw, $timestamp, $sax_auth_key;
	return substr(md5(substr($timestamp, 0, -7).$sax_user.$sax_uid.$sax_pw.$sax_auth_key.$specialadd), 8, 8);
}

//获得某年某月的时间戳
function gettimestamp($year, $month) {
	$start = strtotime($year.'-'.$month.'-1');
	if ($month == 12) {
		$endyear  = $year + 1;
		$endmonth = 1;
	} else {
		$endyear  = $year;
		$endmonth = $month+1;
	}
	$end = strtotime($endyear.'-'.$endmonth.'-1');
	return $start.'-'.$end;
}

function random($length, $numeric = 0) {
	PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
	if($numeric) {
		$hash = sprintf('%0'.$length.'d', mt_rand(1, pow(10, $length) - 1));
	} else {
		$hash = '';
		$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
		$max = strlen($chars) - 1;
		for($i = 0; $i < $length; $i++) {
			$hash .= $chars[mt_rand(0, $max)];
		}
	}
	return $hash;
}

function correcttime($timestamp) {
	global $timeoffset;
	$z = date('Z');
	if ($z != '0') {
		$timestamp = $timestamp - ($z - $timeoffset * 3600);
	} else {
		$timestamp = $timestamp - $timeoffset * 3600;
	}
	return $timestamp;
}

//判断是否为邮件地址
function isemail($email) {
	return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}

//截取字数
function trimmed_title($text, $limit=12, $start=0) {
	if ($limit) {
		$val = csubstr($text, $start, $limit);
		return $val[1] ? $val[0].'...' : $val[0];
	} else {
		return $text;
	}
}

function csubstr($text, $start=0, $limit=12) {
	if (function_exists('mb_substr')) {
		$more = (mb_strlen($text,'UTF-8') > $limit) ? true : false;
		$text = mb_substr($text, $start, $limit, 'UTF-8');
		return array($text, $more);
	} elseif (function_exists('iconv_substr')) {
		$more = (iconv_strlen($text) > $limit) ? true : false;
		$text = iconv_substr($text, $start, $limit, 'UTF-8');
		return array($text, $more);
	} else {
		preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $text, $ar);   
		if(func_num_args() >= 3) {   
			if (count($ar[0])>$limit) {
				$more = true;
				$text = join('',array_slice($ar[0], $start, $limit)); 
			} else {
				$more = false;
				$text = join('',array_slice($ar[0], $start, $limit)); 
			}
		} else {
			$more = false;
			$text =  join('',array_slice($ar[0], $start)); 
		}
		return array($text, $more);
	} 
}

//转换字符
function char_cv($string) {
	$string = htmlspecialchars(sax_addslashes($string));
	return $string;
}

//页面输出
function PageEnd() {
	global $options;
	$output = str_replace(array('<!--<!---->','<!---->'),array('',''),ob_get_contents());
	ob_end_clean();
	$options['gzipcompress'] ? ob_start('ob_gzhandler') : ob_start();
	echo $output;
	exit;
}

// base64编码函数
function authcode($string, $operation = 'ENCODE') {
	$string = $operation == 'DECODE' ? base64_decode($string) : base64_encode($string);
	return $string;
}

//获取请求来路
function getreferer() {
	global $options;
	if(!$referer && !$_SERVER['HTTP_REFERER']) {
		$referer = $options['url'];
	} elseif (!$referer && $_SERVER['HTTP_REFERER']) {
		$referer = $_SERVER['HTTP_REFERER'];
	} else {
		$referer = htmlspecialchars($referer);
	}
	if(strpos($referer, 'post.php')) {
		$referer = $options['url'];
	}
	return $referer;
}

function submitcheck($var, $cp = 0) {
	if(empty($GLOBALS[$var])) {
		return false;
	} else {
		if ($cp) {
			$msgfunc = 'redirect';
		} else {
			$msgfunc = 'message';
		}
		global $options, $seccode;
		
		if($_SERVER['REQUEST_METHOD'] == 'POST' && (empty($_SERVER['HTTP_REFERER']) || $GLOBALS['formhash'] != formhash() || preg_replace("/https?:\/\/([^\:\/]+).*/i", "\\1", $_SERVER['HTTP_REFERER']) !== preg_replace("/([^\:]+).*/", "\\1", $_SERVER['HTTP_HOST']))) {
			$msgfunc('您的请求来路不正确,无法提交.');
		} else {
        	if($options['seccode']) {
				$clientcode = $GLOBALS['clientcode'];
				if (!$clientcode || strtolower($clientcode) != strtolower($seccode)) {
					$seccode = random(4, 1);
					updatesession();
					$msgfunc('验证码错误,请返回重新输入.', $referer);
				}
        	}
			return true;
		}
	}
}

// 检查链接URL是否符合逻辑
function isurl($url) {
	if($url) {
		if (!preg_match("#^(http|news|https|ftp|ed2k|rtsp|mms)://#", $url)) {
			return false;
		}
		$key = array("\\",' ',"'",'"','*',',','<','>',"\r","\t","\n",'(',')','+',';');
		foreach($key as $value){
			if (strpos($url,$value) !== false){ 
				return false;
				break;
			}
		}
	}
	return true;
}

function updatesession() {
	if(!empty($GLOBALS['sessionupdated'])) {
		return true;
	}
	global $DB, $db_prefix, $sessionexists, $sessionupdated, $sax_hash, $onlineip, $sax_uid, $sax_group, $timestamp, $seccode, $sax_auth_key, $lastactivity;
	if($sessionexists == 1) {
		$DB->query("UPDATE {$db_prefix}sessions SET uid='$sax_uid', groupid='$sax_group', lastactivity='$timestamp', seccode='$seccode' WHERE hash='$sax_hash'");
	} else {
		replacesession(1);
	}
	if($sax_uid && $timestamp - $lastactivity > 7200) {
		$DB->unbuffered_query("UPDATE {$db_prefix}users SET lastip='$onlineip', lastvisit=lastactivity, lastactivity='$timestamp' WHERE userid='$sax_uid'");
	}
	$sessionupdated = 1;
}

function replacesession($insert = 0) {
	global $DB, $db_prefix, $sax_hash, $onlineip, $sax_uid, $sax_group, $timestamp, $seccode, $sax_auth_key;
	$ips = explode('.', $onlineip);
	$DB->query("DELETE FROM {$db_prefix}sessions WHERE hash='$sax_hash' OR lastactivity<($timestamp-900) OR ('$sax_uid'<>'0' AND uid='$sax_uid') OR (uid='0' AND ip1='$ips[0]' AND ip2='$ips[1]' AND ip3='$ips[2]' AND ip4='$ips[3]' AND lastactivity>$timestamp-60) OR (is_robot = '1' AND lastactivity < ($timestamp-900))");
	if ($insert) {
		$DB->query("INSERT INTO {$db_prefix}sessions (hash, auth_key, ip1, ip2, ip3, ip4, uid, groupid, lastactivity, seccode, is_robot) VALUES ('$sax_hash', '$sax_auth_key', '$ips[0]', '$ips[1]', '$ips[2]', '$ips[3]', '$sax_uid', '$sax_group', '$timestamp', '$seccode', '".IS_ROBOT."')");
	}
}

function isrobot() {
	$kw_spiders = 'Bot|Crawl|Spider|Slurp|sohu|Twiceler|lycos|robozilla|Google|baidu|msn|yahoo|sogou';
	$kw_browsers = 'MSIE|Netscape|Opera|Konqueror|Mozilla';
	if(preg_match("/($kw_spiders)/i", $_SERVER['HTTP_USER_AGENT'])) {
		return 1;
	} elseif(preg_match("/($kw_browsers)/i", $_SERVER['HTTP_USER_AGENT'])) {
		return 0;
	} else {
		return 0;
	}
}

// 登录记录
function loginresult($username = '', $result) {
	global $timestamp,$onlineip;
	writefile(SABLOG_ROOT.'cache/log/loginlog.php', "<?PHP exit('Access Denied'); ?>\t$username\t$timestamp\t$onlineip\t$result\n", 'a');
}

function scookie($key, $value, $life = 0, $prefix = 1) {
	global $cookiepre, $cookiedomain, $cookiepath, $timestamp, $_SERVER;
	$key = ($prefix ? $cookiepre : '').$key;
	$life = $life ? $timestamp + $life : 0;
	$useport = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;
	setcookie($key, $value, $life, $cookiepath, $cookiedomain, $useport);
}

// 删除cookies
function dcookies($key = '') {
	global $sax_uid, $sax_user, $sax_pw;
	if ($key) {
		if(is_array($key)) {
			foreach ($key as $name) {
				scookie($name, '', -86400 * 365);
			}
		} else {
			scookie($key, '', -86400 * 365);
		}
	} else {
		if(is_array($_COOKIE)) {
			foreach ($_COOKIE as $key => $val) {
				scookie($key, '', -86400 * 365);
			}
		}
		$sax_uid = 0;
		$sax_user = $sax_pw = '';
	}
}

//读取文件内容
function loadfile($filename, $filesize = 0, $method='rb', $local = 1) {
	$filedata = false;
	if (strpos($filename, '..') !== false) {
		 exit('Load file failed');
	}
	if(function_exists('file_get_contents')) {
		$filedata = @file_get_contents($filename);
	} elseif($local && $fp = @fopen($filename, $method)) {
		flock($fp,LOCK_SH);
		$size = $filesize ? $filesize : filesize($filename);
		$filedata = @fread($fp, $size);
		fclose($fp);
	} elseif(!$local) {
		$filedata = @implode('', file($filename));
	}
	return $filedata;
}

//写入文件内容
function writefile($filename, $data, $method = 'wb', $chmod = 1) {
	$return = false;
	if (strpos($filename, '..') !== false) {
		 exit('Write file failed');
	}
	if($fp = @fopen($filename, $method )) {
		@flock($fp, LOCK_EX);
		$return = fwrite($fp, $data);
		fclose($fp);
		$chmod && @chmod($filename,0777);
	}
	return $return;
}

?>